<?php
require_once('Interface.php');

Zend_Loader::loadClass('Lead_Event_Observer_Abstract');

/**
 * Observable object for an events system. Observable extends Observer,
 * so every observable can also act as an observer.
 * 
 * @category Lead
 * @package Lead_Event
 * 
 *
 */
abstract class Lead_Event_Observable_Abstract extends Lead_Event_Observer_Abstract implements Lead_Event_Observable_Interface
{
	/**
	 * Observers for a specific event.
	 *
	 * @var Array
	 */
	protected $_observers = array();

	
	/**
	 * Attaches an observer to an event.
	 *
	 * @param string $event Event name
	 * @param object $observer Observer object
	 * @param string $method Observer's method to call (default is 'notify').
	 */
	public function attach(Lead_Event_Observer_Interface $observer, $event, $method = 'notify')
	{
		$this->_observers[$event][] = array($observer, $method);
	}
	

	
	/**
	 * Notifies all observers (in other words, triggers an event). The observers' defined handler methods
	 * will receive the observable object as a reference, event's name and the message (which can be
	 * anything, depending on the circumstances).
	 *
	 * @param string $event Event name
	 * @param mixed $msg The message
	 */
	public function notifyAll($event, $msg = null)
	{
		if(isset($this->_observers[$event]))
		{
			foreach($this->_observers[$event] as $callback_array)
			{
				if(is_callable($callback_array))
				{
					call_user_func($callback_array, $this, $event, $msg);			
				}
				else 
				{
				  
				    throw new Lead_Event_Exception("Event '{$event}' is not callable.");
				}
			}			
		}
		
		
	}

	
	
}